package io.chance.receiverlei.schedule;

import io.chance.receiverlei.channel.ChannelManager;
import io.chance.receiverlei.channel.MessageDecode;
import io.chance.receiverlei.channel.MsgReceiverHandler;
import io.chance.receiverlei.db.model.RequestModel;
import lrq.common.MyLog;
import lrq.common.PropertiesUnit;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.HashMap;
import java.util.Map.Entry;

public class AskModbusDataJob implements Job {

    Logger log;
    private int orderInterval = PropertiesUnit.getInt("orderInterval");

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {

        if (log == null) {
            log = MyLog.getLogger(getClass().getSimpleName());
        }

        try {
            @SuppressWarnings("unchecked")
            HashMap<String, Channel> channelMap = (HashMap<String, Channel>) ChannelManager.getChannelMap().clone();
            for (Entry<String, Channel> channelItem : channelMap.entrySet()) {
                String channelId = channelItem.getKey();
                String mn = ChannelManager.getMN(channelId);

                if (mn == null || mn.equals("") || mn.equals("null") || !channelItem.getValue().isOpen() || !channelItem.getValue().isReadable()) {
                    continue;
                }
//                if (Integer.valueOf(mn) < newMinMn) {
                if (!MsgReceiverHandler.isNewMn.containsKey(mn)) {
                    try {
                        for (String funHex : RequestModel.FUNC_HEXs) {
                            ChannelManager.sendByteMsgByMN(mn, MessageDecode.hexToBytes(funHex));
                            log.info(mn + "询问数据:" + funHex);
                            Thread.sleep(orderInterval);
                        }
                    }
                    catch (Exception e) {
                        log.error("询问数据出错", e);
                    }
                }
                else {
                    ChannelManager.sendByteMsgByMN(mn, MessageDecode.hexToBytes(RequestModel.FUNC_HEX_NEW));
                    log.info(mn + "询问数据:" + RequestModel.FUNC_HEX_NEW);
                }
            }
        }
        catch (Exception e) {
            log.error("询问数据出错", e);
        }
    }

    public static String formatNum(String hexStr) {
        if (hexStr.length() == 1) {
            hexStr = "0" + hexStr;
        }
        return hexStr;
    }
}
